
import java.io.File;
import java.io.FileInputStream;
import java.net.*;

public class Hoster extends Thread {

    private Socket socket;

    public static void main(String[] args) {
        new Hoster();
    }

    public Hoster() {
        try {
            ServerSocket server = new ServerSocket(8080);
            while (true) {
                new Hoster(server.accept());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Hoster(Socket socket) {
        System.out.println("");
        System.out.println("");
        System.out.println("****************************************");
        System.out.println("Connect " + socket.getInetAddress().getHostAddress() + " " + socket.getInetAddress().getHostName());

        this.socket = socket;
        start();
    }

    public void run() {
        try {
            String in = "";
            int header = 0;
            while (header < 4) {
                int read = socket.getInputStream().read();
                in += (char) read;
                if (read == 10 || read == 13) {
                    header++;
                } else {
                    header = 0;
                }
            }
            System.out.println("  **  Header start  **");
            System.out.println(in);
            System.out.println("  **  Header end  **");
            if (in.indexOf("GET ") == 0) {
                get(in);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("DONE ALL!");
    }

    public void get(String in) {
        String get = in.substring(in.indexOf("/") + 1);
        get = get.substring(0, get.indexOf(" "));
        if (get.length() == 0) {
            get = "Hoster.html";
        }
        sendFile(get);
    }

    public void sendFile(String fName) {
        System.out.println("Send: " + fName);
        try {
            if (new File("../" + fName).exists()) {
                FileInputStream fIn = new FileInputStream(fName);
                int l = fIn.available();
                System.out.println("File length: " + l);
                byte[] b = new byte[l];
                fIn.read(b);
                fIn.close();
                socket.getOutputStream().write(("HTTP/1.1 200 OK\r\nContent-Length: " + l + "\r\n\r\n").getBytes());
                socket.getOutputStream().write(b);
                System.out.println("Sent!");
            } else {
                System.out.println("File not found!");
                socket.getOutputStream().write(("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n").getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
